package com.mujin.keji.collectionsystem.module.outboundtask.views;

import android.Manifest;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.listeners.CustomItemClickListener;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.BoundTaskAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.TripStatusAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.StatusCountDto;
import com.mujin.keji.collectionsystem.module.outboundtask.viewmodel.BoundTaskListViewModel;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.SelectVo;
import com.mujin.keji.collectionsystem.net.NetworkUtil;
import com.mujin.keji.collectionsystem.permissions.PermissionUtils;
import com.mujin.keji.collectionsystem.permissions.PermissionsObserver;
import com.mujin.keji.collectionsystem.utils.DialogUtils;
import com.mujin.keji.collectionsystem.widget.CustomLazyViewPager;
import com.mujin.keji.collectionsystem.widget.SelectTaskTypPopWindow;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 外访任务列表Activity界面
 *
 * @author weishixiong
 * @Time 2018-03-21
 */
public class OutBoundtaskListActivity extends BaseActivity implements CustomItemClickListener, View.OnClickListener, SelectTaskTypPopWindow.SelectLisenter, BDLocationListener {
    private GridLayoutManager gm_tripstatus;
    private List<Fragment> fragmentList;
    private TripStatusAdapter tripStatusAdapter;
    private BoundTaskAdapter boundTaskAdapter;
    private List<StatusCountDto> mStatusCountDtos;

    public TripStatusAdapter getTripStatusAdapter() {
        return tripStatusAdapter;
    }

    public void setTripStatusAdapter(TripStatusAdapter tripStatusAdapter) {
        this.tripStatusAdapter = tripStatusAdapter;
    }

    public List<StatusCountDto> getmStatusCountDtos() {
        return mStatusCountDtos;
    }

    public void setmStatusCountDtos(List<StatusCountDto> mStatusCountDtos) {
        this.mStatusCountDtos = mStatusCountDtos;
    }

    private RecyclerView rvTripTask;
    //    private LinearLayout llTime;
//    private LinearLayout llDistance;
    private CustomLazyViewPager viewPager;
    //    private EditText etName;
    private BoundTaskListViewModel boundTaskListViewModel;
    private ImageView ivCancel;
    //    private LinearLayout llSelect;
    private LinearLayout llTop;
    private TextView tvOrderAdress;
    private TextView tvOrderName;

    private ImageView ivOrderOne;
    private ImageView ivOrderTwo;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CcsApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.removeActivity(this);
        CcsApplication.getInstance().mLocationClient.stop();
        CcsApplication.getInstance().mLocationClient.unRegisterLocationListener(this);
    }

    @Override
    protected void createViewModel() {
        boundTaskListViewModel = ViewModelProviders.of(this).get(BoundTaskListViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_outboundtasklist;
    }

    @Override
    public void initView() {
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        setCenterTitle("外访任务", "#FFFFFF");

        ivOrderOne = (ImageView) findViewById(R.id.iv_order_one);
        ivOrderTwo = (ImageView) findViewById(R.id.iv_order_two);

        tvOrderAdress = (TextView) findViewById(R.id.tv_order_adress);
        tvOrderName = (TextView) findViewById(R.id.tv_order_name);
        llTop = (LinearLayout) findViewById(R.id.ll_top);
        ivCancel = (ImageView) findViewById(R.id.iv_cancel);
        rvTripTask = (RecyclerView) findViewById(R.id.rv_trip_task);
//        llTime = (LinearLayout) findViewById(R.id.ll_time);
//        llDistance = (LinearLayout) findViewById(R.id.ll_distance);
        viewPager = (CustomLazyViewPager) findViewById(R.id.viewPager);
        viewPager.setScanScroll(false);
//        etName = (EditText) findViewById(R.id.et_name);
//        llSelect = (LinearLayout) findViewById(R.id.ll_select);
//        viewPager.setScanScroll(false);
        viewPager.setOffscreenPageLimit(3);
        initTripListStatus();
        initBoundTaskListView();

    }

    private BaseOutBoundTaskFragment w = new WaiteOutBoundtaskFragment();
    private BaseOutBoundTaskFragment h = new HasOutBoundtaskFragment();
    private BaseOutBoundTaskFragment f = new FinishOutBoundtaskFragment();

    /**
     * 初始化拜访任务各个状态列表试图
     */
    private void initBoundTaskListView() {
        fragmentList = new ArrayList<>();
        fragmentList.add(w);
        fragmentList.add(h);
        fragmentList.add(f);
        boundTaskAdapter = new BoundTaskAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(boundTaskAdapter);
    }

    /**
     * 初始化拜访任务头部列表view
     */
    private void initTripListStatus() {
        mStatusCountDtos = new ArrayList<>();
        mStatusCountDtos.add(new StatusCountDto(0, 1, true));
        mStatusCountDtos.add(new StatusCountDto(0, 2, false));
        mStatusCountDtos.add(new StatusCountDto(0, 3, false));
        gm_tripstatus = new GridLayoutManager(this, 3);
        rvTripTask.setLayoutManager(gm_tripstatus);
        tripStatusAdapter = new TripStatusAdapter(this, mStatusCountDtos, this);
        rvTripTask.setAdapter(tripStatusAdapter);

    }


    @Override
    public void initData() {


    }

    @Override
    protected void onStart() {
        super.onStart();
        getLocationSetting();
        initPermission();
    }

    /**
     * 打开位置设置
     */
    private void getLocationSetting() {
        if (!NetworkUtil.isGpsOPen(this)) {
            CcsApplication.getInstance().mLocationClient.stop();
            //位置信息没有开启
            DialogUtils.showAdressInfoDailog("无法获取当前位置信息，请在手机设置中开启位置信息", OutBoundtaskListActivity.this);
            //Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            //startActivity(intent);

            return;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }


    /**
     * 获取定位权限以及录音，拍照，写文件权限
     */
    private void initPermission() {
        RxPermissions.getInstance(this).request(
                Manifest.permission.RECORD_AUDIO,//录音权限
                Manifest.permission.ACCESS_COARSE_LOCATION, //定位权限
                Manifest.permission.ACCESS_FINE_LOCATION,//定位权限
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//写权限
                Manifest.permission.READ_EXTERNAL_STORAGE, //读权限
                Manifest.permission.READ_PHONE_STATE,//电话权限
                Manifest.permission.CAMERA//相机权限
        ).subscribe(new PermissionsObserver() {
            @Override
            protected void onGetPermissionsSuccess() {
                //开启定位
                CcsApplication.getInstance().mLocationClient.start();
                CcsApplication.getInstance().mLocationClient.registerLocationListener(OutBoundtaskListActivity.this);
            }

            @Override
            protected void onGetPermissionsSuccessFailuer() {
                if (!PermissionUtils.hasPermission(OutBoundtaskListActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, OutBoundtaskListActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(OutBoundtaskListActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, OutBoundtaskListActivity.this);
                    return;
                }

                if (!PermissionUtils.hasPermission(OutBoundtaskListActivity.this, new String[]{Manifest.permission.CAMERA})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.CAMERA_MESSAGE, OutBoundtaskListActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(OutBoundtaskListActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.EXTERNAL_MESSAGE, OutBoundtaskListActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(OutBoundtaskListActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.EXTERNAL_MESSAGE, OutBoundtaskListActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(OutBoundtaskListActivity.this, new String[]{Manifest.permission.RECORD_AUDIO})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.RECORD_MESSAGE, OutBoundtaskListActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(OutBoundtaskListActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.PHONE_MESSAGE, OutBoundtaskListActivity.this);
                    return;
                }
            }
        });
    }

    // 0 地址降序 1 地址升序  2 姓名降序 3 姓名升序
    private int orderBy;


    public int getOrderBy() {
        return orderBy;
    }

    public void setOrderBy(int orderBy) {
        this.orderBy = orderBy;
    }

    @Override
    public void initListener() {
        tvOrderAdress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (orderBy == 0) {
                    orderBy = 1;
                    ivOrderOne.setImageResource(R.drawable.image_order_up);
                } else {
                    orderBy = 0;
                    ivOrderOne.setImageResource(R.drawable.image_order_bottom);
                }
                ivOrderTwo.setImageResource(R.drawable.image_order_bottom);
                tvOrderAdress.setTextColor(getResources().getColor(R.color.color_main_title));
                tvOrderName.setTextColor(getResources().getColor(R.color.color_text_dark));
                setOrderBy(orderBy);


                int posision = viewPager.getCurrentItem();
                if (posision == 0) {
                    w.refleshData();
                }
                if (posision == 1) {
                    h.refleshData();
                }
                if (posision == 2) {
                    f.refleshData();
                }


            }
        });
        tvOrderName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (orderBy == 2) {
                    orderBy = 3;
                    ivOrderTwo.setImageResource(R.drawable.image_order_up);
                } else {
                    orderBy = 2;
                    ivOrderTwo.setImageResource(R.drawable.image_order_bottom);
                }
                ivOrderOne.setImageResource(R.drawable.image_order_bottom);

                tvOrderName.setTextColor(getResources().getColor(R.color.color_main_title));
                tvOrderAdress.setTextColor(getResources().getColor(R.color.color_text_dark));
                setOrderBy(orderBy);

                int posision = viewPager.getCurrentItem();
                if (posision == 0) {
                    w.refleshData();
                }
                if (posision == 1) {
                    h.refleshData();
                }
                if (posision == 2) {
                    f.refleshData();
                }

            }
        });
//        llDistance.setOnClickListener(this);
//        llTime.setOnClickListener(this);
        //实时搜索功能
//        RxTextView.textChanges(etName)
//                //监听输入完1秒之后发送事件
//                .debounce(1, TimeUnit.SECONDS)
//                //跳过输入框EditText 初始化的的时候产生的事件。
//                .skip(1)
//                //把观察者切换到UI线程
//                .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
//                .subscribe(new rx.Observer<CharSequence>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onNext(CharSequence charSequence) {
//                        String str = charSequence.toString();
//                        SearchVo searchVo = new SearchVo(str);
//                        EventBus.getDefault().post(searchVo);
//                    }
//                });
//
//        etName.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                if (!EmptyUtils.isNotEmpty(s.toString())) {
//                    ivCancel.setVisibility(View.GONE);
//                } else {
//                    ivCancel.setVisibility(View.VISIBLE);
//                }
//            }
//        });
//        ivCancel.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                etName.setText(null);
//            }
//        });
    }


    @Override
    public void onItemClick(View view, int position) {
        reflushSelectView(position);

    }

    /**
     * 根据点击拜访任务的状态，刷新试图
     *
     * @param position 点击的那个postion
     */
    private void reflushSelectView(int position) {
        for (int i = 0; i < mStatusCountDtos.size(); i++) {
            if (position == i) {
                mStatusCountDtos.get(i).setSelected(true);
            } else {
                mStatusCountDtos.get(i).setSelected(false);
            }
        }
        tripStatusAdapter.notifyDataSetChanged();
        viewPager.setCurrentItem(position);
    }

    @Override
    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.ll_distance:
//                new SelectTaskTypPopWindow(this, mOne_position, mTwo_position, viewPager.getMeasuredHeight(), this, "2").showAsDropDown(llSelect);
//                break;
//            case R.id.ll_time:
//                new SelectTaskTypPopWindow(this, mOne_position, mTwo_position, viewPager.getMeasuredHeight(), this, "1").showAsDropDown(llSelect);
//                break;
//        }
    }

    private int mOne_position = 0;
    private int mTwo_position = 0;

    @Override
    public void onSelect(int one_position, int two_position, int selectType) {
        this.mOne_position = one_position;
        this.mTwo_position = two_position;
        SelectVo selectVo = new SelectVo(selectType);
        EventBus.getDefault().post(selectVo);
    }

    private String loacationAdress;

    public String getLoacationAdress() {
        return loacationAdress;
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation != null) {
            //获取定位地址
            loacationAdress = bdLocation.getAddrStr();
            CcsApplication.getInstance().mLocationClient.stop();

        }
    }
}
